<template>
    <div class="searchPage">
      <!-- header -->
      <div class="search_header">
        <van-nav-bar
          title="商品搜索"
          left-arrow
          @click-left="$router.go(-1)"
        />
      </div>
      <!-- search body -->
      <div class="search_body">
        <van-search
          v-model="search"
          show-action
          placeholder="请输入您要搜索的商品"
          @click="onSearch()"
        >
          <template #action>
            <div class="search_but" @click="onSearch(search)">搜索</div>
          </template>
        </van-search>
      </div>
      <!-- history -->
      <div v-if="history.length > 0" class="search_history">
        <div class="history_title">
          <span>最近搜索</span>
          <van-icon @click="clear()" name="delete-o" class="del_icon" size="24"/>
        </div>
        <div class="history_item">
            <!-- <button v-for="item in history"
            :key="item"
            @click="onSearch(item)">
              {{ item }}
            </button> -->
            <van-grid :column-num="3" gutter="10" clickable>
              <van-grid-item
                v-for="item in history"
                :key="item"
                :text="item"
                @click="onSearch(item)"
              />
            </van-grid>
          </div>
      </div>
    </div>
</template>

<script>
import { getHistory, setHistory } from '@/utils/storage'

export default {
  name: 'SearchIndex',
  data () {
    return {
      search: '',
      history: getHistory()
    }
  },
  methods: {
    onSearch (key) {
      if (!key) {
        return
      }
      const index = this.history.indexOf(key)
      if (index !== -1) {
        // 已存在
        this.history.splice(index, 1)
      }
      this.history.unshift(key)
      setHistory(this.history)
      this.$router.push(`/list?search=${key}`)
    },
    clear () {
      this.history = []
      setHistory([])
    }
  }

}
</script>

<style scoped>
  /* ::v-deep .van-nav-bar__title{
    font-size: 50px;
    color: #e70c0c;
  } */
  .van-search .van-cell{
    font-size: 20px;
    height: 50px;
    line-height: 50px;
  }
  .search_but{
    height: 50px;
    width: 60px;
    border-radius: 0 7px 7px 0;
    color: #fff;
    font-size: 24px;
    text-align: center;
    line-height: 50px;
    background-color: red;
  }
  .history_title{
    margin: 10px;
    font-size: 18px;
    display: flex;
    justify-content: space-between;
    align-content: center;
  }
  /* .history_item{
    margin: 10px;
    display: flex;
  } */
  .van-grid-item__text{
    /* padding: 3px; */
    /* border-radius: 7px;
    margin-right: 15px; */
    font-size: 30px;
  }
</style>
